<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>canvas实现圆周运动</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<canvas id="canvas">你的浏览器不支持canvas，请跟换其他浏览器试一试</canvas>

<script>

    window.onload = function () {
        var canvas = document.getElementById('canvas');
        canvas.height = 728;
        canvas.width = 1024;
        var context = canvas.getContext('2d');
        // 绘制原始小红球
        drawNotChange(context);
        // 绘制小篮球
        context.fillStyle = 'blue';
        context.beginPath();
        context.arc(500, 550, 30, 0, 2 * Math.PI, true);
        context.closePath();
        context.fill();
        setInterval(function () {
            run(context);
        }, 50);
    };

    var time = 0;//定义运动的执行次数

    /**
     * 定时器函数
     * @param cxt
     */
    function run(cxt) {

        cxt.clearRect(0, 0, 1024, 728);
        drawNotChange(cxt);
        //将当前以左上角坐标为(0,0)的上下文环境进行保存
        cxt.save();
        cxt.translate(500, 400);
        //设定每次旋转的度数
        cxt.rotate(time * 8 * Math.PI / 180);
        cxt.fillStyle = 'blue';
        cxt.beginPath();
        cxt.arc(0, 150, 30, 0, 2 * Math.PI, false);
        cxt.closePath();
        cxt.fill();
        //在save中就是将上下文环境保存到栈中，在restore下面对其进行还原
        cxt.restore();
        time += 1;
    }

    /**
     * 绘制小红球
     * @param context
     */
    function drawNotChange(context) {
        context.fillStyle = 'red';
        context.beginPath();
        context.arc(500, 400, 30, 0, 2 * Math.PI, true);
        context.closePath();
        context.fill();
        context.beginPath();
        context.arc(500, 400, 150, 0, 2 * Math.PI, true);
        context.closePath();
        context.stroke();
    }
</script>
</body>
</html>